package com.yien.springstudy.executor;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池util
 *
 * @author Miaoxiong Fan
 * @since version
 */

public class ExecutorUtil {

    private static ScheduledThreadPoolExecutor poolExecutor = new ScheduledThreadPoolExecutor(1);
    private static ScheduledFuture<?> startFuture;


    public static void startTask1() {
        ScheduledFuture<?> future = poolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程池任务1调度执行");
            }
        }, 1, 3, TimeUnit.SECONDS);
        startFuture = future;
    }

    public static void startTask2() {
        ScheduledFuture<?> future = poolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程池任务2调度执行");
            }
        }, 1, 3, TimeUnit.SECONDS);
        startFuture = future;
    }


    public static void cancelTaskByFuture() {
        if(startFuture != null) {
            System.out.println("线程池任务状态是否停止："+startFuture.isCancelled());
            if (!startFuture.isCancelled()) {
                System.out.println("停止线程池任务");
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                startFuture.cancel(false);
            }
            System.out.println("线程池任务状态是否停止："+startFuture.isCancelled());
            System.out.println("线程池任务状态是否完成："+startFuture.isDone());
        }
    }

    public static void main(String[] args) {
        System.out.println("main线程开始");
        startTask1();
        System.out.println("main线程其他的操作");
        cancelTaskByFuture();
        startTask2();
        cancelTaskByFuture();
    }


}
